<template>
  <div class="page">
      <div class="edit-normal-client-main" :style="containerHeight" id="edit-normal-client-main">
        <group>
          <cell v-if="client.nick_name" title="昵称" v-model="client.nick_name" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></cell>
          <cell title="家长姓名" v-model="client.parent_name" placeholder="请输入家长姓名" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></cell>
          <cell title="是否学员" v-model="client.is_member" novalidate :icon-type="iconType" :show-clear="false">
            <slot>{{ client.is_member == 1 ? '是' : '否'}}</slot>
          </cell>
          <cell title="手机号码" v-model="client.mobile_num" placeholder="输入手机号码" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></cell>
          <!-- <cell class="address" title="所在地址" :value="client.address" placeholder="请输入地址" raw-value :list="addressData" placeholder-align="right"></cell> -->
          <cell title="所属行业" placeholder="请输入所属行业" :options="industryOptions" v-model="client.parent_industry" placeholder-align="right"></cell>

          <cell direction="rtl" title="客户来源" placeholder="请选择客户来源" :options="clientSourceOptions" :value="customSources[client.source_id]" placeholder-align="right" ></cell>
          <cell direction="rtl" title="跟进状态" placeholder="请选择跟进状态" :options="customStatusOptions" :value="getCustomStatus(client.custom_status)" placeholder-align="right" ></cell>
          <cell direction="rtl" title="客户属性" placeholder="请选择客户属性" :options="customPropertyOptions" :value="getCustomProperty(client.custom_property)" placeholder-align="right" ></cell>
          <cell title="详细地址"  class="address-field" :value="(client.province || '') + (client.city || '') + (client.district || '') + (client.address || '')" placeholder-align="right"></cell>
          <!-- <cell title="创建人" placeholder="输入创建人" novalidate :icon-type="iconType" v-model="client.creator" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></cell> -->
        </group>

        <div class="weui-cells-no-margin" v-for="(baby, index) in this.babies" :key="index">
          <div class="weui-cells__title"  slot="after-title">
            宝宝: {{ baby.baby_name }}
          </div>
          <group >
            <cell  title="宝宝姓名" v-model="baby.baby_name" placeholder="输入宝宝姓名" placeholder-align="right"  :show-clear="false" @on-blur="onBlur" ></cell>
            <cell  name="experience_time" direction="rtl" title="宝宝性别" :value="babyGenders[baby.baby_sex]" placeholder="输入宝宝性别"  :options="babyGenderOptions" placeholder-align="right"></cell>
            <cell confirmText="完成" cancelText="取消"title="宝宝生日" :value = "baby.baby_birthday" placeholder="请选择宝宝生日" placeholder-align="left"></cell>
          </group>
        </div>

        <!-- <div class="btn-group center-btn-group" v-if="client.mobile_num">
          <a class="btn scrm-default-btn" :href="'tel:' + client.mobile_num ">拨打电话</a>
        </div> -->

      </div>

      <x-dialog v-model="this.$store.state.app.dialogShow" >
        <div class="dialog-message">
          {{ this.$store.state.app.dialogMessage }}
        </div>
        <span class="vux-close" @click="hideDialog">知道了</span>
      </x-dialog>
    </div>
</template>

<script>
  // import Vue from 'vue'
  // import clientMenu from '../components/client-menu'
  import {showDialog, hideDialog} from '../lib/dialog'
  import {cleanClient} from '../lib/client'
  // import {XInput, XDialog, Group, ChinaAddressData, XAddress, Selector, Datetime} from 'vux'

  import Cell from 'vux/src/components/cell'
  import Group from 'vux/src/components/group'
  // import XAddress from 'vux/src/components/x-address'
  import ChinaAddressData from 'vux/src/datas/china_address.json'
  // import Selector from 'vux/src/components/cell'
  // import Datetime from 'vux/src/components/datetime'
  import XDialog from 'vux/src/components/x-dialog'

  import store from '../store'
  // import VeeValidate from 'vee-validate'
  import { validateClient } from '../lib/validate-rules'

  export default{
    data () {
      return {
      containerHeight : 'min-height:'+document.body.scrollHeight+'px;',
      id: '',
      client:{
        name: '',
        parent_name: '',
        phone: '',
        address: '',
        babyGenderValue:'',
        birthday: '',
        iconType: '',
        source_id: '',
        baby_name: '',
        parent_industry: '',
        babyGenderValue: '',
        address: '',
        custom_status: '',
        custom_property: '',
        creator: '',
      },
      baby: {
        baby_sex: 'MALE###',
        baby_name: '',
        baby_birthday : new Date().toLocaleDateString()
      },
      errors: {
        babies: {}
      },
      babies:[],
      iconType: '',
      addressData : ChinaAddressData,

      address: ['广东省', '深圳市', '南山区'],

      // source_id: '',
      // parent_industry: '',
      // babyGenderValue: '',

      babyGenderOptions: [
        {
          key : 'MALE###',
          value: '男'
        },
        {
          key: 'FEMALE#',
          value: '女'
        }
      ],

      babyGenders: {
        'MALE###': '男',
        'FEMALE#': '女',
        'UNKNOWN': '未知'
      },

      industryOptions : [

        {
        key: 'IT',
        value:'IT软件业'
        },

        {
        key:'hairdressing',
        value:'美容美甲'}
      ],

      clientSourceOptions: [],

      followStatus : [

        {
        key: 'followed',
        value:'已跟进'
        },

        {
        key:'unfollowed',
        value:'未跟进'}
      ],

      followProperties : [

        {
        key: 0,
        value:'意向客户'
        },

        {
        key:1,
        value:'我的客户'
        }
      ],
      }
    },
    components: {
      Cell,
      Group,
      ChinaAddressData,
      // XAddress,
      // Selector,
      // Datetime,
      XDialog
    },
    methods: {
      refresh (iscroll) {
        console.log('refresh')
        // Refresh current data
      },
      hideDialog: hideDialog,
      log () {
        console.log('ee');
      },

      load (iscroll) {
        console.log('load')
        // Load new data
      },

      test () {
        console.log('test')
      },
      getCustomStatus (status) {
        let customStatus = '暂无跟进'
        this.customStatusOptions.forEach((elem, index) => {
          if (elem.key === status) customStatus = elem.value
        })
        return customStatus
      },
      getCustomProperty (property) {
        let customProperty = '一般客户'
        this.customPropertyOptions.forEach((elem, index) => {
          if (elem.key === property) customProperty = elem.value
        })
        return customProperty
      },
      deleteBaby (baby, index) {
        if(this.babies.length>1) {
          this.babies.splice(index, 1)
        } else {
          console.log(this.custom_type, 'ssss')
          if(this.custom_type === 1) {
            showDialog('必须保留一个宝宝喔!');
            setTimeout(() => {   hideDialog() },3300)
          } else {
            this.babies = []
          }
        }
      },

      validate () {
        if(this.custom_type === 0 && this.babies.length === 0) {
          this.errors.babies = []
        }
        return this.$el.getElementsByClassName('weui-cell_warn').length === 0
      },

      onBlur () {
      },
      addBaby () {
        let newBaby = Object.assign({}, this.baby)
        this.babies.push(newBaby);
      },
      onShow () {
        console.log(arguments)
      },
      //初始化客户信息
      initClientInfo (id) {
        this.$vux.loading.show({text: '加载中...'})
        setTimeout(() => {
          this.$vux.loading.hide()
        }, 12000)
        let that = this;
        store.dispatch('getCustomInfoById', id)
          .then(function(response){
            if(response.data.errcode === 0) {
              let client = response.data.results;
              that.client = client;
              that.initAddress();
              that.client.custom_type = that.custom_type == 1 ? 'QT#' : 'WX#';
              that.client.operator_id = that.loginUser.id
              that.client.operator_name = that.loginUser.name
              that.client.creator = that.loginUser.name
              console.log(JSON.stringify(that.loginUser))
            } else {
              console.debug('系统服务异常！请联系管理员!', JSON.stringify(response.data));
            }
          }).catch(function(error){
            console.log(error)
          })
      },

      initAddress () {
        // this.client.address = [this.client.province, this.client.city, this.client.district].join('');
      },

      initBabyInfo (id) {
        let that = this;
        let query = this.$route.query
        store.dispatch('getBabys', id)
          .then((response) => {
            if(response.data.errcode == 0) {
              that.babies = response.data.results;
              that.custom_type = query.custom_type;
              if(this.babies.length === 0)  {
                this.addBaby()
              }
            } else {
              console.log('服务器错误！请联系管理员!');
            }
            this.$vux.loading.hide()
          }).catch(() => {
            this.$vux.loading.hide()
          })
      },

      submit () {
        let id = this.id;
        let that = this;
        let isValid = this.validate()

        if(isValid === false) {
          return ;
        }

        if(this.saveLock) {
          showDialog('提交中....');
          setTimeout(() => {
            hideDialog()
          },300)
          return ;
        }

        this.saveLock = true
        console.debug('that.client', JSON.stringify(that.client))
        console.debug('that.babies', JSON.stringify(that.babies))

        store.dispatch('saveClientInfo', cleanClient(that.client)).then(function(aresponse){
          if(aresponse.data.errcode == 0) {
            let params = {info:that.babies, id : id}
            store.dispatch('saveBabys', params).then(function(response){
              if(response.data.errcode == 0) {
                console.debug('保存成功！');
                showDialog('保存成功!')

                setTimeout(() => {
                  hideDialog();
                  that.$router.back()
                }, 2000)

              } else {
                console.log('保存宝宝信息失败!', JSON.stringify(response.data))
                showDialog(response.data.errmsg);
              }
            }).catch((error) =>{
              that.saveLock = false
              console.log(error)
            });
          } else {
            console.log('保存客户信息失败!', JSON.stringify(aresponse.data))
          }

          that.saveLock = false

        }).catch((error) =>{
          console.log(error)
          that.saveLock = false
        });
      },

      saveClientInfo () {
        this.errors = validateClient(this.client, this.babies)

        setTimeout(() => {
          this.submit()
        })
      }

    },

    beforeMount () {
      store.dispatch('getCustomSource')
    },

    mounted () {
      let query =  this.$route.query;
      let id = query.id;

      this.id = id;
      this.initClientInfo(id);
      this.initBabyInfo(id);

    },

    computed : {
      //包含客户详情的列表
      clientsDetail () {
        return this.$store.state.app.clientsDetail;
      },

      //跟进状态选项列表
      customStatusOptions() {
        return this.$store.state.app.customStatusOptions;
      },

      //客户属性选项列表
      customPropertyOptions() {
        return this.$store.state.app.customPropertyOptions;
      },

      loginUser () {
        return this.$store.state.app.user;
      },

      customSources () {
        return this.$store.state.app.customSources;
      }

    },

    watch:{
      customSources () {
        let customSources = this.customSources
        for (let id in customSources) {
          let source = customSources[id]
          this.clientSourceOptions.push({
            key: id,
            value: source
          })
        }
      }
    }

  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .edit-normal-client-main {
    padding-bottom: 20px;

    .no-margin{
       &>*{
       margin: 0
       }
    }

    .add-new-btn{
      width: 60%;
    }

    .btn-group{
      &:extend(.clearfix all);
      margin-top: 15px;

      &>*{
        width: 80%;
        text-align: center;
        border-radius: 4px;
        padding: 10px;
        margin: 0 auto;
      }

      .babayArea {
        &:extend(.clearfix all);
        border-top: 1px solid #ccc;
      }

      .pull-left{
        float: left;
      }

      .pull-right{
        float: right;
      }
    }

    .delete-baby {
      float: right;
      color: #39ADFF;
    }

  }
</style>
